package client;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Observable;

import network.message.IMessage;

/**
 * This class is a basic client that has been modified to work specifically with the setback program. 
 * @author JFIELD
 *
 */
public class BasicClient extends Observable
{
	private Socket server;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	
    /**
     *  Connects to the given host:port
     *  @param host - the host to connect to.
     *  @param port - the port to connect to.
     *  @throws IOException - if the a socket can't be opened. 
     */
    public void connect(String host, int port) throws IOException 
    {
            server = new Socket(host, port);
            oos = new ObjectOutputStream(server.getOutputStream());
            ois = new ObjectInputStream(server.getInputStream());
    }
    
    /**
     * Sends an object to the server.
     * @param outgoing - the outgoing message.
     */
    public void send(IMessage outgoing) 
    {
        try 
        {
            oos.reset();
            oos.writeObject(outgoing);
            oos.flush();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }

    /**
     * Receives an object from the server. 
     * @return - the object received from the server.
     */
    public IMessage recieve() 
    {
        IMessage retVal = null;
        Object recv;
        try 
        {
            recv = ois.readObject();
            if(recv instanceof IMessage)
            {
            	retVal = (IMessage)recv;
            }
            else
            {
            	throw new IllegalArgumentException();
            }
        }
        catch(EOFException e)
        {
            close();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
        }

        return retVal;
    }
    
    /**
     * Closes the socket and its underlying connections.
     */
    public void close()
    {
        try 
        {
            oos.close();
            ois.close();
            server.close();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    
}
